sap.ui.define([
	"sap/ui/core/mvc/Controller",
	"../model/formatter",
], function (
	Controller,
	formatter
) {
	"use strict";

	return Controller.extend("firorworkshop185.controller.OrderSearch", {
		formatter: formatter,

		onInit: function () {
			var oEventBus = sap.ui.getCore().getEventBus();
			oEventBus.subscribe("overViewEventChannel", "initSearch", this.initSearch, this);
			oEventBus.subscribe("overViewEventChannel", "goSearchPress", this.GoPress, this);
		},


		onAfterRendering: function () {
			$("#" + this.getView().getId() + "--" + "hideOrderFilterBar").show();
			$("#" + this.getView().getId() + "--" + "showOrderFilterBar").hide();
			$("#" + this.getView().getId() + "--" + "myForm").show();
		},

		/**
		 * 筛选Input相关的方法开始
		 */
		initSearch: function () {
			let sourceList = formatter.objectTransformToList(this.getView().getModel("ENTITY001Set"));

			let uniStatusList = this.uniSearchItem(sourceList, "statusNo");
			var oStatusMultiComboBox = this.getView().byId("statusMultiComboBox");
			let statusChoosedList = oStatusMultiComboBox.getSelectedItems().map(element => {
				return element.mProperties.key
			});
			oStatusMultiComboBox.removeAllItems();
			uniStatusList.forEach(element => {
				var oItem = new sap.ui.core.Item({
					key: element,
					text: element
				});
				oStatusMultiComboBox.addItem(oItem);
			});
			oStatusMultiComboBox.setSelectedKeys(statusChoosedList);


			let uniCustomerList = this.uniSearchItem(sourceList, "customerNo");
			var oCustomerMultiComboBox = this.getView().byId("customerMultiComboBox");
			let customerChoosedList = oCustomerMultiComboBox.getSelectedItems().map(element => {
				return element.mProperties.key
			});
			oCustomerMultiComboBox.removeAllItems();
			uniCustomerList.forEach(element => {
				var oItem = new sap.ui.core.Item({
					key: element,
					text: element
				});
				oCustomerMultiComboBox.addItem(oItem);
			});
			oCustomerMultiComboBox.setSelectedKeys(customerChoosedList);

			let uniRepPersonList = this.uniSearchItem(sourceList, "repPersonNo");
			var oRepPersonMultiComboBox = this.getView().byId("repairPersonMultiComboBox");
			let repPersonChoosedList = oRepPersonMultiComboBox.getSelectedItems().map(element => {
				return element.mProperties.key
			});
			oRepPersonMultiComboBox.removeAllItems();
			uniRepPersonList.forEach(element => {
				var oItem = new sap.ui.core.Item({
					key: element,
					text: element
				});
				oRepPersonMultiComboBox.addItem(oItem);
			});
			oRepPersonMultiComboBox.setSelectedKeys(repPersonChoosedList);
		},

		uniSearchItem(list, key) {
			let keyList = list.map(element => {
				if (element[key] != "") {
					return element[key];
				} else {
					return "UNNECESSARY"
				}
			});
			// list去重
			return [...new Set(keyList)];
		},

		GoPress() {
			var oProductNumberMultiInput = this.getView().byId("productNumberMultiInput");
			let productNumberChoosedList = oProductNumberMultiInput.getTokens().map(element => {
				return element.mProperties.key
			});

			var oStatusMultiComboBox = this.getView().byId("statusMultiComboBox");
			let statusChoosedList = oStatusMultiComboBox.getSelectedItems().map(element => {
				return element.mProperties.key
			});

			var oCustomerMultiInput = this.getView().byId("customerMultiComboBox");
			let customerChoosedList = oCustomerMultiInput.getSelectedItems().map(element => {
				return element.mProperties.key
			});

			var oRepPersonMultiInput = this.getView().byId("repairPersonMultiComboBox");
			let repPersonChoosedList = oRepPersonMultiInput.getSelectedItems().map(element => {
				return element.mProperties.key
			});

			// 因为我这里是将OrderList和OrderSearch是分成两个视图模块写的
			// 而每个模块所对应的controller里使用this.getView().byId()方法只能获取该xml模块里定义的组件
			// 所以我这里只能先找到orderSearch的父级视图Overview,在这个父级视图下有OrderList和OrderSearch两个子视图
			// 我再通过该父级视图找到OrderList子视图
			// 因为暂时找不到更好的解决方法，只有这样通过路径去手动寻找了
			var oTable = this.getView().oParent.mAggregations.items[1].byId("ordersTable");

			var oBinding = oTable.getBinding("items");
			var aFilters = oBinding.aFilters;

			let alreadyFilterList = [formatter.objectTransformToList(aFilters)[0]];
			// 这里我将idIconTabBar的筛选条件永远置于第一个
			alreadyFilterList = this.addFilterList(alreadyFilterList, productNumberChoosedList, "productID");
			alreadyFilterList = this.addFilterList(alreadyFilterList, statusChoosedList, "statusNo");
			alreadyFilterList = this.addFilterList(alreadyFilterList, customerChoosedList, "customerNo");
			alreadyFilterList = this.addFilterList(alreadyFilterList, repPersonChoosedList, "repPersonNo");

			// 变化IconFilterTab上的数据
			// 显示IconFilterTab的count数据时不把FilterTab，也就是filterList里的第一个数据加上
			let alreadyFilterList1 = alreadyFilterList.slice(1, alreadyFilterList.length);
			oBinding.filter(alreadyFilterList1);
			let IconFilterTabList = []
			oTable.getBinding("items").aIndices.forEach(element => {
				IconFilterTabList.push(oTable.getBinding("items").oList[element])
			});
			var oEventBus = sap.ui.getCore().getEventBus();
			oEventBus.publish("overViewEventChannel", "initIconTabBar", IconFilterTabList);


			oBinding.filter(alreadyFilterList);

			// 变化title上的数据总数
			var oTitle = oTable.getHeaderToolbar().mAggregations.content[0];
			oTitle.setText("Orders (" + (oTable.getBinding("items").getLength() || 0) + ")");
		},

		addFilterList(alreadyFilterList, choosedList, key) {
			if (choosedList.length == 0) {
				return alreadyFilterList
			} else {
				let filterList = [];
				choosedList.forEach(element => {
					if (element != "UNNECESSARY") {
						filterList.push(new sap.ui.model.Filter(key, sap.ui.model.FilterOperator.EQ, element));
					} else {
						filterList.push(new sap.ui.model.Filter(key, sap.ui.model.FilterOperator.EQ, ""));
					}
				});
				alreadyFilterList.push(new sap.ui.model.Filter(filterList, false)); // false表示逻辑或
				return alreadyFilterList;
			}
		},

		hideFilterBar() {
			$("#" + this.getView().getId() + "--" + "myForm").hide();
			$("#" + this.getView().getId() + "--" + "hideOrderFilterBar").hide();
			$("#" + this.getView().getId() + "--" + "showOrderFilterBar").show();

			var oScrollContainer = this.getView().oParent.mAggregations.items[1].byId("orderListScrollContainer");
			oScrollContainer.setHeight("calc(100vh - 210px)");
		},

		showFilterBar() {
			$("#" + this.getView().getId() + "--" + "myForm").show();
			$("#" + this.getView().getId() + "--" + "hideOrderFilterBar").show();
			$("#" + this.getView().getId() + "--" + "showOrderFilterBar").hide();

			var oScrollContainer = this.getView().oParent.mAggregations.items[1].byId("orderListScrollContainer");
			oScrollContainer.setHeight("calc(100vh - 300px)");
		},

		clearAllOrderSearchInput() {
			this.getView().byId("statusMultiComboBox").removeAllSelectedItems();
			this.getView().byId("customerMultiComboBox").removeAllSelectedItems();
			this.getView().byId("repairPersonMultiComboBox").removeAllSelectedItems();
			this.getView().byId("productNumberMultiInput").removeAllTokens();
			this.GoPress();
		},

		productNumberMultiInputTokenUpdate(oEvent) {
			var oProductNumberMultiInput = this.getView().byId("productNumberMultiInput");
			var filteredList1 = oProductNumberMultiInput.getTokens().filter(function (item) {
				return oEvent.mParameters.removedTokens.indexOf(item) === -1;
			});
			console.log(filteredList1);
			var oProductNumberMultiInput = this.getView().byId("productNumberMultiInput");
			oProductNumberMultiInput.setTokens(filteredList1);
			this.GoPress();
		},

		/**
		 * 筛选Input相关的方法结束
		 */

		/**
		 * ProductNumber控件相关的方法开始
		 */
		handleProductNumberValueHelp(oEvent) {
			var oProductNumberMultiInput = this.getView().byId("productNumberMultiInput");
			let tokenList = [];

			var sourceList = formatter.objectTransformToList(this.getView().getModel("ENTITY002Set"));
			let sourceObj = {};
			sourceList.forEach(element => {
				sourceObj[element.productID] = element.productName;
			});
			oProductNumberMultiInput.getTokens().forEach(element => {
				tokenList.push(new sap.m.Token({ text: sourceObj[element.mProperties.key] + "(" + element.mProperties.key + ")", key: element.mProperties.key }));
			});


			var sInputValue = oEvent.getSource().getValue(),
				oView = this.getView();

			var that = this;

			if (!this._pValueHelpDialog) {
				this._pValueHelpDialog = this.loadFragment({
					// id: "ValueHelpDialog",
					name: "firorworkshop185.view.fragment.ProductNumberValueHelp",
					controller: this
				}).then(function (oValueHelpDialog) {
					oView.addDependent(oValueHelpDialog);
					return oValueHelpDialog;
				});
			}


			this._pValueHelpDialog.then(function (oValueHelpDialog) {

				// that.sFragmentId = oValueHelpDialog.getId();
				// 使用该方法可以在该函数里将数据保存在全局变量里
				oValueHelpDialog.open(sInputValue);

				$("#" + that.getView().getId() + "--" + "hideProductFilterButton").show();
				$("#" + that.getView().getId() + "--" + "showProductFilterButton").hide();

				var oMultiInput = sap.ui.core.Fragment.byId(that.getView().getId(), "selectedProductMultInput");
				oMultiInput.setTokens(tokenList);

				sap.ui.core.Fragment.byId(that.getView().getId(), "productNumberInput").setValue("");
				sap.ui.core.Fragment.byId(that.getView().getId(), "productNameInput").setValue("");
				sap.ui.core.Fragment.byId(that.getView().getId(), "productCategoryInput").setValue("");
				sap.ui.core.Fragment.byId(that.getView().getId(), "searchField").setValue("");
			});
		},

		doProductSearch() {
			// 由于此处调用该方法时该fragment一定是打开状态，所以不需要下面四行代码便能获取
			// 如果该fragment没有使用过open()方法，便需要下面四行代码
			// if (this._oValueHelpDialog) {
			// 	this._oValueHelpDialog.destroy();
			// }
			// this._oValueHelpDialog = sap.ui.xmlfragment(this.getView().getId(), "firorworkshop185.view.fragment.ProductNumberValueHelp", this); // 加载Fragment
			// 在这个方法中，第一个参数必须与下面的第一个参数保持一致,第二个参数是fragment的路径，第三个参数是this


			// 如果想要通过ID获取Fragment里面的组件，只有用下面的办法
			var oTable = sap.ui.core.Fragment.byId(this.getView().getId(), "ProductTable");
			// 这样写的意义便是打开id为'this.getView().getId() + "ProductTable"'的组件
			// 第二个参数是我手动为该组件设置的id，第一个参数是因为这样才能拼接成需要的id
			// 其实这边主要还是在浏览器里查看对应组件的id,然后发现该组件的id是这样子拼接的

			var productNumberInput = sap.ui.core.Fragment.byId(this.getView().getId(), "productNumberInput")._lastValue;
			var productNameInput = sap.ui.core.Fragment.byId(this.getView().getId(), "productNameInput")._lastValue;
			var productCategoryInput = sap.ui.core.Fragment.byId(this.getView().getId(), "productCategoryInput")._lastValue;
			var searchInput = sap.ui.core.Fragment.byId(this.getView().getId(), "searchField").mProperties.value;
			let obj = {
				productNumber: productNumberInput,
				productName: productNameInput,
				productCategory: productCategoryInput,
				searchInput: searchInput
			}

			// 获取multInput中选中的项目，将其设置为默认选中
			var oMultiInput = sap.ui.core.Fragment.byId(this.getView().getId(), "selectedProductMultInput");
			let list = []
			oMultiInput.getTokens().forEach(element => {
				list.push(element.mProperties.key);
			});

			// 使用这个方法可以调用control组件里的方法
			oTable.filterList(obj, list);
		},

		chooseMode(oEvent) {
			console.log(oEvent.getSource().getSelectedContexts());
		},

		hideProductFilter() {
			$("#" + this.getView().getId() + "--" + "productForm").hide();
			$("#" + this.getView().getId() + "--" + "hideProductFilterButton").hide();
			$("#" + this.getView().getId() + "--" + "showProductFilterButton").show();
		},

		showProductFilter() {
			$("#" + this.getView().getId() + "--" + "productForm").show();
			$("#" + this.getView().getId() + "--" + "showProductFilterButton").hide();
			$("#" + this.getView().getId() + "--" + "hideProductFilterButton").show();
		},

		fatherSelectionChange(controlItem) {
			var oMultiInput = sap.ui.core.Fragment.byId(this.getView().getId(), "selectedProductMultInput");
			let yetlist = []
			oMultiInput.getTokens().forEach(element => {
				yetlist.push({
					text: element.mProperties.text,
					key: element.mProperties.key
				})
			});
			if (yetlist.filter(item => item.key == controlItem.mParameters.value.productID).length !== 0) {
				yetlist = yetlist.filter(item => item.key != controlItem.mParameters.value.productID)
			} else {
				yetlist.push({
					text: controlItem.mParameters.value.productName + "(" + controlItem.mParameters.value.productID + ")",
					key: controlItem.mParameters.value.productID
				})
			}
			oMultiInput.removeAllTokens();
			let tokenList = []
			yetlist.forEach(item => {
				tokenList.push(new sap.m.Token({ text: item.text, key: item.key }));
			});
			oMultiInput.setTokens(tokenList);
		},

		fatherDeleteAllItems(controlItem) {
			var oMultiInput = sap.ui.core.Fragment.byId(this.getView().getId(), "selectedProductMultInput");
			let yetlist = []
			oMultiInput.getTokens().forEach(element => {
				yetlist.push({
					text: element.mProperties.text,
					key: element.mProperties.key
				})
			});
			controlItem.mParameters.value.forEach(element => {
				yetlist = yetlist.filter(item => item.key != element.productID)
			});
			oMultiInput.removeAllTokens();
			let tokenList = []
			yetlist.forEach(item => {
				tokenList.push(new sap.m.Token({ text: item.text, key: item.key }));
			});
			oMultiInput.setTokens(tokenList);
		},

		fatherSelectAllOptions(controlItem) {
			var oMultiInput = sap.ui.core.Fragment.byId(this.getView().getId(), "selectedProductMultInput");
			let yetlist = []
			oMultiInput.getTokens().forEach(element => {
				yetlist.push({
					text: element.mProperties.text,
					key: element.mProperties.key
				})
			});
			controlItem.mParameters.value.forEach(element => {
				if (yetlist.filter(item => item.key == element.productID).length == 0) {
					yetlist.push({
						text: element.productName + "(" + element.productID + ")",
						key: element.productID
					})
				}
			});
			oMultiInput.removeAllTokens();
			let tokenList = []
			yetlist.forEach(item => {
				tokenList.push(new sap.m.Token({ text: item.text, key: item.key }));
			});
			oMultiInput.setTokens(tokenList);
		},

		tokenUpdate(oEvent) {
			var oTable = sap.ui.core.Fragment.byId(this.getView().getId(), "ProductTable");
			if (oEvent.mParameters.type == "removed") {
				oEvent.mParameters.removedTokens.forEach(element => {
					oTable.withMultInputChange(element.mProperties.key);
				});
			}
		},

		removeAllMultiInput() {
			var oTable = sap.ui.core.Fragment.byId(this.getView().getId(), "ProductTable");
			var oMultiInput = sap.ui.core.Fragment.byId(this.getView().getId(), "selectedProductMultInput");
			oMultiInput.getTokens().forEach(element => {
				oTable.withMultInputChange(element.mProperties.key);
			});
			oMultiInput.removeAllTokens();
		},

		onProductNumberConfirm() {
			var oMultiInput = sap.ui.core.Fragment.byId(this.getView().getId(), "selectedProductMultInput");
			let tokenList = [];

			oMultiInput.getTokens().forEach(element => {
				tokenList.push(new sap.m.Token({ text: element.mProperties.key, key: element.mProperties.key }));
			});
			var oProductNumberMultiInput = this.getView().byId("productNumberMultiInput");
			oProductNumberMultiInput.setTokens(tokenList);

			sap.ui.core.Fragment.byId(this.getView().getId(), "valueHelpDialog").close();
			this.GoPress();
		},

		onProductNumberCancel() {
			sap.ui.core.Fragment.byId(this.getView().getId(), "valueHelpDialog").close();
		},

		/**
		 * ProductNumber控件相关的方法结束
		 */
	});
});